//
//  RGXOneController.m
//  JiCaiBao
//
//  Created by rgx on 16/10/21.
//  Copyright © 2016年 rgx. All rights reserved.
//

#import "RGXOneController.h"
#import "RGXNavigationController.h"
#import "MJRefresh.h"
#import<CommonCrypto/CommonDigest.h>
#import "SDCycleScrollView.h"
#import "RGXSSQController.h"
#import "RGXQlcController.h"

@interface RGXOneController (){
    
    NSMutableArray *urlImages;
    NSMutableArray *h5UrlStrings;
    NSMutableArray *titleArr;
    
    NSString *newsUrl;  //最新资讯入口地址
}

@end

@implementation RGXOneController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    RGXLog(@"Hello");
    // 网络加载 --- 创建自定义图片的pageControlDot的图片轮播器
    
    self.bannerView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    
    self.bannerView.delegate = self;
    
    self.bannerView.currentPageDotColor = [UIColor whiteColor]; // 自定义分页控件小圆标颜色
    self.bannerView.placeholderImage = [UIImage imageNamed:@"yct_banner"];
//    self.bannerView.currentPageDotImage = [UIImage imageNamed:@"pageControlCurrentDot"];
//    self.bannerView.pageDotImage = [UIImage imageNamed:@"pageControlDot"];
    
    __weak __typeof(self) weakSelf = self;
    //         --- 模拟加载延迟
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        //加载数据
        [weakSelf queryNewsScrollData];
        
    });
    
    // Do any additional setup after loading the view from its nib.
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
    self.baseScrollView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    
    // 马上进入刷新状态
    [self.baseScrollView.mj_header beginRefreshing];

    [self queryNewsList];
}

- (void)loadNewData{
    
    [self.baseScrollView.mj_header endRefreshing];
    
}


- (void)queryNewsScrollData
{
    __weak RGXOneController *selfInfo = self;

    
    NSMutableDictionary *body = [NSMutableDictionary dictionary];
    [body setObject:@"0" forKey:@"scrollType"];
    
    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    [securityPolicy setAllowInvalidCertificates:YES];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager POST:NewsScroll parameters:body progress:^(NSProgress * uploadProgress) {
        
    } success:^(NSURLSessionDataTask * task, id responseObject) {
        
        // 请求成功
        if(responseObject){
            RGXLog(@"responseObject:轮播图 = %@",responseObject);
            [selfInfo handleImg:responseObject];
            
        } else {
            RGXLog(@"无数据");
        }
        
    } failure:^(NSURLSessionDataTask * task, NSError * error) {
        RGXLog(@"error = %@",error);
    }];
    
    
}

- (void)handleImg:(NSDictionary *)data
{
    if (![data isKindOfClass:[NSDictionary class]]) {
        return;
    }
    if (![[data objectForKey:@"statusCode"] isEqualToString:@"0000"]) {
        return;
    }
    NSArray *listArr = [data objectForKey:@"body"];
    if (listArr.count == 0) {
        return;
    }
    
    //    图片中数
    NSInteger totalCount = listArr.count;
    
    if (urlImages) {
        [urlImages removeAllObjects];
    }else{
        urlImages = [[NSMutableArray alloc]init];
    }
    if (h5UrlStrings) {
        [h5UrlStrings removeAllObjects];
    }else{
        h5UrlStrings = [[NSMutableArray alloc]init];
    }
    if (titleArr) {
        [titleArr removeAllObjects];
    }else{
        titleArr = [[NSMutableArray alloc]init];
    }
    //    添加图片
    for (int i = 0; i < totalCount; i++) {
        
        //设置图片
        NSString *imgUrl = [[listArr objectAtIndex:i] objectForKey:@"image_url"];
        NSString *string_h5Url = [[listArr objectAtIndex:i] objectForKey:@"url"];
        NSString *title = [[listArr objectAtIndex:i] objectForKey:@"title"];
        [urlImages addObject:imgUrl];
        [h5UrlStrings addObject:string_h5Url];
        [titleArr addObject:title];
    }
    
    self.bannerView.imageURLStringsGroup = urlImages;
    
}

#pragma  mark ---  newsList
- (void)queryNewsList
{
    __weak RGXOneController *selfInfo = self;
    
    
    NSMutableDictionary *body = [NSMutableDictionary dictionary];
    [body setObject:@"" forKey:@"classId"]; //栏目类别ID,可传空
    [body setObject:@"0" forKey:@"from"];   //开始记录数，默认传0
    [body setObject:@"1" forKey:@"size"];   //条数
    
    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    [securityPolicy setAllowInvalidCertificates:YES];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager POST:NewsList parameters:body progress:^(NSProgress * uploadProgress) {
        
    } success:^(NSURLSessionDataTask * task, id responseObject) {
        
        // 请求成功
        if(responseObject){
            RGXLog(@"responseObject:新闻列表 = %@",responseObject);
            [selfInfo handleNewsData:responseObject];
        } else {
            RGXLog(@"无数据");
        }
        
    } failure:^(NSURLSessionDataTask * task, NSError * error) {
        RGXLog(@"error = %@",error);
    }];
    

}
- (void)handleNewsData:(NSDictionary *)data{
    
    if (![data isKindOfClass:[NSDictionary class]]) {
        return;
    }
    if (![[data objectForKey:@"statusCode"] isEqualToString:@"0000"]) {
        return;
    }
    NSArray *listArr = [data objectForKey:@"body"];
    if (listArr.count == 0) {
        return;
    }
    for (NSDictionary *dict in listArr) {
        self.newsLabel.text = [NSString stringWithFormat:@": %@",[dict objectForKey:@"title"]];
        newsUrl = [NSString stringWithFormat:@"%@",[dict objectForKey:@"url"]];
    }
    
}

#pragma mark - SDCycleScrollViewDelegate

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    RGXLog(@"---点击了第%ld张图片", (long)index);
    
    CYWebViewController *actCtrl = [[CYWebViewController alloc] init];
    NSString *h5webapp = [h5UrlStrings objectAtIndex:index];
//    h5webapp = @"https://tower.im/teams/b5587484bd254b879c59523dcb0184d3/events/";
    actCtrl.url = [NSURL URLWithString:h5webapp];
    
    RGXLog(@"轮播图跳转地址：%@",h5webapp);
    actCtrl.loadingBarTintColor = [UIColor whiteColor];
    [self.navigationController pushViewController:actCtrl animated:YES];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)newsClick:(id)sender {
    
    CYWebViewController *actCtrl = [[CYWebViewController alloc] init];
    
    actCtrl.url = [NSURL URLWithString:newsUrl];
    actCtrl.loadingBarTintColor = [UIColor whiteColor];
    
    [self.navigationController pushViewController:actCtrl animated:YES];
}

- (IBAction)xyxhClick:(id)sender {
    
    CYWebViewController *actCtrl = [[CYWebViewController alloc] init];
    
    actCtrl.url = [NSURL URLWithString:@"http://m.yzfcw.com/ssq/lucky.php?client=ios"];
    actCtrl.loadingBarTintColor = [UIColor whiteColor];
    
    [self.navigationController pushViewController:actCtrl animated:YES];
}

- (IBAction)zztjClick:(id)sender {
    
    CYWebViewController *actCtrl = [[CYWebViewController alloc] init];
    
    actCtrl.url = [NSURL URLWithString:@"http://m.yzfcw.com/recommend/?client=ios&userId=1111&sessionId=1111"];
    actCtrl.loadingBarTintColor = [UIColor whiteColor];
    
    [self.navigationController pushViewController:actCtrl animated:YES];
    
}

- (IBAction)ssqClick:(id)sender {
    
    RGXSSQController *ssqVC = [[RGXSSQController alloc]initWithNibName:@"RGXLotteryController" bundle:nil];
    RGXNavigationController *nav = [[RGXNavigationController alloc] initWithRootViewController:ssqVC];
    
    [self presentViewController:nav animated:YES completion:^{
        RGXLog(@"双色球选号");

    }];
}

- (IBAction)k3Click:(id)sender {
    
}

- (IBAction)fc3dClick:(id)sender {
    
}

- (IBAction)qlcClick:(id)sender {
    
    RGXQlcController *qlcVC = [[RGXQlcController alloc]initWithNibName:@"RGXQlcController" bundle:nil];
    RGXNavigationController *nav = [[RGXNavigationController alloc] initWithRootViewController:qlcVC];
    
    [self presentViewController:nav animated:YES completion:^{
        RGXLog(@"七乐彩选号");
        
    }];
}

@end
